<script setup lang="ts">
import { ref, computed } from 'vue';
import { useAsyncData } from '@/home/hooks/async-data';
import { useFetch } from '@/home/hooks/fetch';
import InteractBtn from './InteractBtn.vue';

export interface EngagementData {
  informationLikeCount: number;
  informationCollections: number;
  informationViews: number;
  informationCommentCount: number;
  isLike: boolean;
  isCollect: boolean;
}

const props = defineProps({
  id: {
    type: String,
    default: '',
  },

  enableComment: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['click', 'change']);

const { $fetch } = useFetch();
const loading = ref(false);

const { data: detail, refresh } = useAsyncData<EngagementData>(
  'explore:journalism:detail:sidePanel:engagement',
  () => $fetch<EngagementData>('/information/like/num', { data: { informationId: props.id } }),
  {
    cache: false,
    watch: [() => props.id],
  },
)

/**
 * 用于生成点赞和收藏的点击事件, 当用户未登录时跳转到登录页
 * @param type 1: 点赞 2: 收藏
 */
const saveEngagement = async (type: number) => {
  if (loading.value) {
    return;
  }

  loading.value = true;

  const { isSuccess } = await $fetch('/information/like', {
    method: 'post',
    params: {
      informationId: props.id,
      type,
    },
    autoGotoLogin: true,
  });

  loading.value = false;

  if (isSuccess) {
    await refresh();
    emit('change', { ...detail.value });
  }
};

const commentEnabled = computed(() => props.enableComment);

defineExpose({
  refresh: () => {
    refresh();
  },
});
</script>

<template>
  <aside class="component-side-panel sticky top-40vh h-[fit-content]">
    <div class="flex flex-col gap-y-16" v-if="detail">
      <InteractBtn
        :title="$t('home.explore.journalism.sidePanel.like')"
        :num="detail.informationLikeCount"
        :icon-class="`i-icons:good ${detail.isLike ? 'c-primary-1!' : 'c-gray-1'}`"
        :num-class="detail.isLike ? 'bg-primary-1' : 'bg-hex-dbdbdb'"
        hover
        @click="saveEngagement(1)"
      />
      <InteractBtn
        :title="$t('home.explore.journalism.sidePanel.favorite')"
        :num="detail.informationCollections"
        :icon-class="`i-icons:favorite ${detail.isCollect ? 'c-hex-FFD700!' : 'c-gray-1'}`"
        :num-class="detail.isCollect ? 'bg-primary-1' : 'bg-hex-dbdbdb'"
        hover
        @click="saveEngagement(2)"
      />
      <InteractBtn
        :num="detail.informationCommentCount"
        icon-class="i-icons:comment-outlined-2 c-gray-1"
        num-class="bg-hex-dbdbdb"
        hover
        @click="emit('click', 'comment')"
        v-if="commentEnabled"
      />
    </div>
  </aside>
</template>

<style lang="scss" scoped>
</style>
